package com.example.cardgame;
import java.util.Random;
public class CardGameModel {
    private int[][] cards; // 卡片数组，存储图片资源ID
    private boolean[][] flipped; // 记录卡片是否被翻开
    private int score;
    private int flippedCount; // 当前翻开的卡片数量
    private int firstFlippedRow = -1;
    private int firstFlippedCol = -1;
    private int matchedPairs;
    private static final int TOTAL_PAIRS = 8;

    public CardGameModel() {
        cards = new int[4][4];
        flipped = new boolean[4][4];
        initializeCards();
    }

    private void initializeCards() {
        // 创建8对卡片
        int[] cardValues = {
                R.drawable.card_1, R.drawable.card_2, R.drawable.card_3, R.drawable.card_4,
                R.drawable.card_5, R.drawable.card_6, R.drawable.card_7, R.drawable.card_8,
                R.drawable.card_1, R.drawable.card_2, R.drawable.card_3, R.drawable.card_4,
                R.drawable.card_5, R.drawable.card_6, R.drawable.card_7, R.drawable.card_8
        };

        // 随机打乱数组
        shuffleArray(cardValues);

        // 填充卡片数组
        int index = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                cards[i][j] = cardValues[index++];
                flipped[i][j] = false;
            }
        }

        score = 0;
        flippedCount = 0;
        matchedPairs = 0;
    }

    private void shuffleArray(int[] array) {
        Random random = new Random();
        for (int i = array.length - 1; i > 0; i--) {
            int index = random.nextInt(i + 1);
            int temp = array[index];
            array[index] = array[i];
            array[i] = temp;
        }
    }

    public int getCard(int row, int col) {
        return cards[row][col];
    }

    public boolean isFlipped(int row, int col) {
        return flipped[row][col];
    }

    public void flipCard(int row, int col) {
        flipped[row][col] = true;
        flippedCount++;

        if (flippedCount == 1) {
            firstFlippedRow = row;
            firstFlippedCol = col;
        } else if (flippedCount == 2) {
            // 检查是否匹配
            if (cards[firstFlippedRow][firstFlippedCol] == cards[row][col]) {
                // 匹配成功
                score += 10;
                matchedPairs++;
                flippedCount = 0;
            } else {
                // 匹配失败
                score = Math.max(0, score - 2);
            }
        }
    }

    public void resetFlippedCount() {
        flippedCount = 0;
    }

    public void unflipCard(int row, int col) {
        flipped[row][col] = false;
    }

    public int getScore() {
        return score;
    }

    public boolean isGameCompleted() {
        return matchedPairs == TOTAL_PAIRS;
    }

    public void resetGame() {
        initializeCards();
    }

    public int getFirstFlippedRow() {
        return firstFlippedRow;
    }

    public int getFirstFlippedCol() {
        return firstFlippedCol;
    }
}